package com.whiteblue.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.whiteblue.common.Const;
import com.whiteblue.interceptor.UserCheckInterceptor;
import com.whiteblue.model.User;
import com.whiteblue.validator.LoginValidator;
import com.whiteblue.validator.RegistValidator;
import com.whiteblue.validator.UpdateUserValidator;

/**
 * Created with IntelliJ IDEA.
 */
public class UserController extends Controller {
	public void index() {
		setAttr("user", User.dao.get(getParaToInt(0, 0)));
		render("/user_info.html");
	}

	@Before(LoginValidator.class)
	public void login() {

		String id = getPara("id");
		String password = getPara("password");
		User user = User.dao.getByPassword(id, password);
		if (user != null) {
			String bbsID = id + Const.BBS_ID_SEPARATOR + password;
			setCookie("bbsID", bbsID, 3600 * 24 * 30);
			setSessionAttr("user", user);
			setSessionAttr("userID", user.get("id"));
			redirect("/");
		} else {
			setAttr("msg", "用户名或密码错误");
			render("/login.html");
		}
	}

	public void logout() {
		removeSessionAttr("user");
		removeSessionAttr("userID");
		removeCookie("bbsID");
		redirect("/");
	}

	@Before(RegistValidator.class)
	public void save() {
		User user = getModel(User.class);
		user.mySave();
		setAttr("msg", "恭喜你，注册成功，请登录：");
		render("/login.html");
	}

	@Before(UserCheckInterceptor.class)
	public void edit() {
		setAttr("user", User.dao.get(getParaToInt(0, 0)));
		render("/user_info_edit.html");
	}

	@Before(UpdateUserValidator.class)
	public void update() {
		User user = getModel(User.class);
		user.myUpdate();
		setAttr("user", user);
		render("/user_info.html");
	}
}
